/**
 * 
 */
package com.xiaotu.spider;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.InflaterInputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.alibaba.fastjson.JSONObject;
/**  
 * @author wangyanlong
 * @date 2019年7月22日 下午6:12:00
 *
*/
public class SpiderAiqiyiDanMu {
	
	/*public static void main(String[] args) {
        String url = "http://www.iqiyi.com/v_19rrmm2vbk.html";
        List<String> res = getDanMu(url);
        for (String r : res) {
            System.out.println(r);
        }
    }*/

    public static List<String> getDanMu(String url) {
        //获取电影或者电视剧的tvId
       /* String res = httpGetRequest(url, false);
        String REGEX = "tvId:(.+?),";
        Pattern p = Pattern.compile(REGEX);
        Matcher m = p.matcher(res);
        String tvId = "";
        if (m.find()) {
            tvId = m.group(1);
        } else {
            return null;
        }*/
        // 根据tvId获取电影或者电视剧的详细信息。
        //String infoUrl = "http://mixer.video.iqiyi.com/jp/mixin/videos/" + tvId;
    	String infoUrl = "http://mixer.video.iqiyi.com/jp/mixin/videos/3250160600";
        String info = httpGetRequest(infoUrl, false);
        info = info.replace("var tvInfoJs=", "");
        JSONObject jsonObject = JSONObject.parseObject(info);
        // 电影或电视剧专辑
        String albumId = jsonObject.getString("albumId");
        // 电影或电视剧频道
        String channelId = jsonObject.getString("channelId");
        // 电影或电视剧时长
        int duration = jsonObject.getIntValue("duration");
        return getDanMu("3250160600", albumId, channelId, duration);
    }

    private static List<String> getDanMu(String tvId, String albumId, String channelId, int duration) {
        // 弹幕下载地址
        String IQIYI_GET_DANMU_URL = "http://cmts.iqiyi.com/bullet/%s/%s/%s_300_%s.z?rn=%s&business=danmu&is_iqiyi=true&is_video_page=true&tvid=%s&albumid=%s&categoryid=%s&qypid=01010021010000000000";
        List<String> danmus = new ArrayList<String>();
        // 根据电影或电视剧的时长计算出需要多少个批量弹幕请求，爱奇艺平均5分钟请求一次加载弹幕
        int page = duration / (60 * 5) + 1;
        for (int i = 1; i <= page; i++) {
            try {
                String t = "0000" + tvId;
                int length = t.length();
                String first = t.substring(length - 4, length - 2);
                String second = t.substring(length - 2);
                String rn = "0." + randomNum(16);
                String danmuUrl = String.format(IQIYI_GET_DANMU_URL, first, second, tvId, i, rn, tvId, albumId,
                        channelId);
                String res = httpGetRequest(danmuUrl, true);
                if (res != null) {
                    danmus.add(res);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return danmus;
    }

    // httpClient 请求
    private static String httpGetRequest(String url, boolean needUnzip) {
        CloseableHttpClient httpClient = HttpClients.custom().build();
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                if (needUnzip) {
                    return new String(decompress(entity.getContent()));
                }
                return EntityUtils.toString(entity);
            }
        } catch (Exception e) {
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    // 解压缩字节流
    private static byte[] decompress(InputStream is) {
        InflaterInputStream iis = new InflaterInputStream(is);
        ByteArrayOutputStream o = new ByteArrayOutputStream(1024);
        try {
            int i = 1024;
            byte[] buf = new byte[i];
            while ((i = iis.read(buf, 0, i)) > 0) {
                o.write(buf, 0, i);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return o.toByteArray();
    }

    // 构造随机参数
    private static String randomNum(double n) {
        double s = Math.pow(10, n - 1);
        double e = Math.pow(10, n) - 1;
        double res = Math.random() * (e - s) + s;
        NumberFormat nf = NumberFormat.getInstance();
        nf.setGroupingUsed(false);
        return nf.format(res);
    }
    
    
    private static void find() throws Exception {
        Document document = getDocument();
        NodeList list = document.getElementsByTagName("bulletInfo");
        for (int i = 0; i < list.getLength(); i++) {
            Element element = (Element) list.item(i);
            System.out.println(element.getAttribute("contentId"));
          /*  student.setExamid(element.getAttribute("examid"));
            student.setIdcart(element.getAttribute("idcard"));
            student.setName(element.getElementsByTagName("name").item(0).getTextContent());
            student.setLocation(element.getElementsByTagName("location").item(0).getTextContent());
            student.setGrade(element.getElementsByTagName("grade").item(0).getTextContent());*/
        }
    }

    private static Document getDocument() throws ParserConfigurationException,
            IOException, org.xml.sax.SAXException {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(new File("D:/danmu.xml"));
       // Element e = document.getDocumentElement();
        return document;
    }
    
    public static void main(String[] args) throws Exception {
    	//创建一个文档解析器工厂
        DocumentBuilderFactory fac= DocumentBuilderFactory.newInstance();

        //用上面的工厂创建一个文档解析器
        DocumentBuilder builder=fac.newDocumentBuilder();

        //用上面的文档解析器解析一个文件放到document对象里
        Document doc=builder.parse("D:/danmu.xml");

        //获取文档中节点名称为Listener的所有节点，并返回一个节点集合
        NodeList listenerList=doc.getElementsByTagName("bulletInfo");
        System.out.println("一共有"+listenerList.getLength()+"个节点");

        //遍历整个集合(把所有标签名为Listener的节点一个一个拿出来
        for (int i=0;i<listenerList.getLength();i++){
            System.out.println("===========这是第"+(i+1)+"个listener节点的开始:===========");
            //把集合里的每一个listener节点分别拿出来
            Node node=listenerList.item(i);
            //再把上一个节点中的所有属性拿出来
            NamedNodeMap nodeMap= node.getAttributes();
            System.out.println("第"+(i+1)+"个节点一共有"+nodeMap.getLength()+"个属性");

            //遍历所有属性
            for(int j=0;j<nodeMap.getLength();j++){
                Node node1=nodeMap.item(j);
                System.out.println("第"+(j+1)+"个属性的名称是"+node1.getNodeName());
                System.out.println("第"+(j+1)+"个属性的值是"+node1.getNodeValue());
            }
            //获取节点的所有子节点，注意会把所有换行符也解析为子节点
            NodeList childNode=node.getChildNodes();
            
            //遍历所有子节点
            for(int k=0;k<childNode.getLength();k++){
               if(childNode.item(k).getNodeType()==Node.ELEMENT_NODE){
                 //这个过滤条件是只将标签节点保留（换行符的节点就删去）    
                 }

            System.out.println("===========这是第"+(i+1)+"个节点的结束:===========");
            }
        }
    }
}
